package com.example.jetpack.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState

class RepoPagingSource(private val gitHubService: GitHubService):PagingSource<Int,Repo>() {
    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? = null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val repoResponse = gitHubService.searchRepos(page,pageSize)
            val repoItems = repoResponse.items
            val prevkey = if (page > 1) page -1 else null
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null
            LoadResult.Page(data = repoItems, prevKey =  prevkey, nextKey =  nextKey)
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }
}